<!--
 * @Author: ૮₍ ˙О˙₎ა
 * @Date: 2023-07-15 15:33:47
-->
<template>
  <div>
    <el-card>
      <CategoryView />
    </el-card>
    <el-card class="cardTop" v-show="isShowList">
      <el-button
        type="primary"
        :icon="Plus"
        @click="showCard"
        :disabled="category3Id ? false : true"
        >添加属性</el-button
      >

      <el-table :data="attrList" border stripe>
        <el-table-column type="index" label="序号" width="70" />
        <el-table-column prop="attrName" label="属性名称" width="180" />
        <el-table-column prop="attrValueList" label="属性值名称列表">
          <template #default="{ row }">
            <el-tag type="success" v-for="item in row.attrValueList" :key="item.id">{{
              item.valueName
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" #default="{ row }">
          <el-button type="warning" :icon="Edit" @click="updateAttr(row)" />
          <el-button type="danger" :icon="Delete" @click="delAttr(row.id)" />
        </el-table-column>
      </el-table>
    </el-card>

    <el-card class="cardTop" v-show="!isShowList">
      <el-form :inline="true" label-width="55px" :model="addEmitParams">
        <el-form-item label="属性名">
          <el-input placeholder="请输入属性名" v-model="addEmitParams.attrName" />
        </el-form-item>
        <br />
        <el-form-item>
          <el-button type="primary" @click="addEmitValueName">添加属性值</el-button>
          <el-button type="primary" @click="changeAttrShow">取消</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="addEmitParams.attrValueList" border stripe>
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column label="属性值名称">
          <template #default="{ row, $index }">
            <el-input
              ref="inputRef"
              v-model="row.valueName"
              v-if="row.isEdit"
              @blur="toSpan(row, $index)"
              @keyup.enter="toSpan(row, $index)"
            />
            <span style="display: block" v-else @click="toInput(row)">{{ row.valueName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row, $index }">
            <el-popconfirm :title="`确定要${row.valueName}删除吗?`" @confirm="delAttrItem($index)">
              <template #reference>
                <el-button type="danger" :icon="Delete" circle />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-row class="cardTop">
        <el-button type="primary" @click="saveAddAndUpdate">保存</el-button>
        <el-button type="primary" @click="changeAttrShow">取消</el-button>
      </el-row>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { reqDeleteAttr } from '@/api/attr'
import { reqAttrInfoList, reqSaveAttrInfo } from '@/api/attr'
import { useAttrStore } from '@/stores/attr'
import type { IAttrInfoList } from '@/types/attr'
import type { IAttrValueList } from '@/types/attr'
import { Delete, Edit, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, type InputInstance } from 'element-plus'
import { storeToRefs } from 'pinia'
import { nextTick, ref, watch } from 'vue'

// 卡片切换属性
const isShowList = ref(true)

// 获取input实例
const inputRef = ref<InputInstance>()

// 添加和编辑参数搜集
const addEmitParams = ref<IAttrInfoList>({
  attrName: '',
  attrValueList: [],
  categoryId: '',
  categoryLevel: 3
})

// 点击添加属性值按钮
const addEmitValueName = () => {
  addEmitParams.value.attrValueList.push({
    valueName: '',
    isEdit: true
  })
  nextTick(() => {
    inputRef.value?.focus()
  })
}

const toSpan = (row: IAttrValueList, index: number) => {
  if (row.valueName?.trim() === '') {
    ElMessage.closeAll()
    ElMessage.error('输入的值不能为空')
    addEmitParams.value.attrValueList.splice(index, 1)
    return
  }
  const flag = addEmitParams.value.attrValueList.some((item) => {
    if (item !== row) {
      return item.valueName === row.valueName
    }
  })
  if (flag) {
    ElMessage.closeAll()
    ElMessage.error('输入的值不能重复')
    addEmitParams.value.attrValueList.splice(index, 1)
  }
  row.isEdit = false
}
const toInput = (row: IAttrValueList) => {
  row.isEdit = true
  nextTick(() => {
    inputRef.value?.focus()
  })
}

// 删除一列属性
const delAttr = (id: number) => {
  ElMessageBox.confirm('确定要删除吗', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res = await reqDeleteAttr(id)

      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
        getAttrList()
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

// 保存按钮
const saveAddAndUpdate = async () => {
  if (addEmitParams.value.attrName.trim() === '') {
    ElMessage.closeAll()
    ElMessage.error('属性名不能为空')
    return
  }
  if (addEmitParams.value.attrValueList.length === 0) {
    ElMessage.closeAll()
    ElMessage.error('添加属性值不能为空')
    return
  }
  const res = await reqSaveAttrInfo(addEmitParams.value)
  if (res.code === 200) {
    ElMessage.success(addEmitParams.value.id ? '修改成功' : '添加成功')
    getAttrList()
    isShowList.value = true
  }
}

// 删除一个属性值
const delAttrItem = (index: number) => {
  addEmitParams.value.attrValueList.splice(index, 1)
}

// 取消按钮
const changeAttrShow = () => {
  addEmitParams.value.attrName = ''
  addEmitParams.value.attrValueList = []
  addEmitParams.value.categoryId = ''
  addEmitParams.value.id = ''
  isShowList.value = true
}

// 修改属性
const updateAttr = (row: IAttrInfoList) => {
  isShowList.value = false
  addEmitParams.value = row
}

//属性列表中的 点击添加属性
const showCard = () => {
  isShowList.value = false
  addEmitParams.value.categoryId = category3Id.value
}
//#region
// 属性列表
const attrList = ref<IAttrInfoList[]>([])

// 获取属性store
const attrStore = useAttrStore()
const { category1Id, category2Id, category3Id } = storeToRefs(attrStore)

// 获取属性方法
const getAttrList = async () => {
  const res = await reqAttrInfoList(
    category1Id.value as number,
    category2Id.value as number,
    category3Id.value as number
  )
  if (res.code === 200) {
    attrList.value = res.data
  }
}
watch(
  category3Id,
  (newVal) => {
    if (!newVal) {
      attrList.value = []
    } else {
      getAttrList()
    }
  },
  {
    immediate: true
  }
)
//#endregion
</script>

<script lang="ts">
export default {
  name: 'AttrView'
}
</script>

<style lang="scss" scoped>
.cardTop,
.el-table {
  margin-top: 18px;
}
</style>
